package com.hzhk.happyrent.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.ZMModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.ui.activity.rent.LoadWebViewActivity;
import com.hzhk.happyrent.utils.Code;
import com.hzhk.happyrent.utils.MyPerference;
import com.tamic.novate.Throwable;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TextActivity extends AppCompatActivity {


    @BindView(R.id.zm_get)
    Button zmGet;
    @BindView(R.id.text)
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_SCORE_GET, params, new MyStringResponse(this) {
            @Override
            public void onNext(Object tag, String response) {
                CodeModel codeModel=new Gson().fromJson(response, CodeModel.class);
                if(0==codeModel.getErrCode()){
                    ZMModel zmModel=new Gson().fromJson(response, ZMModel.class);
                    text.setText(zmModel.getData());
                    zhima_cer();
//                    Intent intent = new Intent(TextActivity.this, LoadWebViewActivity.class);
//                    intent.putExtra("uil", zmModel.getData());
//                    startActivityForResult(intent, 1);
                }else{
                    doit();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });

    }
    public void zhima_cer(){
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("url", "http://www.taobao.com");
        HttpManager.getInstance().perform_post(API.ZHIMA_CER, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                Log.i("----error",e.getMessage());
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                Log.i(TAG, "onNext: " + response);
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    doVerify(zmModel.getData());
                }
            }
        });
    }
    /**
     * 启动支付宝进行认证
     *
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivityForResult(action,1);
        } else {
            //处理没有安装支付宝的情况
            new AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }

    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List<ResolveInfo> list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

    private void doit() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_AUTH, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                Log.i(TAG, "onNext: " + response);
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    Intent intent = new Intent(TextActivity.this, LoadWebViewActivity.class);
                    intent.putExtra("uil", zmModel.getData());
//            context.startActivity(intent);
                    startActivityForResult(intent, 0);
                }
            }
        });
//        new TestZhimaCustomerCertificationQuery(this).testZhimaAuthInfoAuthorize();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(0==requestCode){
//            initView();
        }else if(1==requestCode){
            zhima_cer_query();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void zhima_cer_query() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().perform_post(API.ZHIMA_CER_QUERY, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(Object tag, String response) {
                Log.i(TAG, "onNext: " + response);
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == codeModel.getErrCode()) {
                    ZMModel zmModel = new Gson().fromJson(response, ZMModel.class);
                    text.setText(zmModel.getData());
                }
            }
        });
//        new TestZhimaCustomerCertificationQuery(this).testZhimaAuthInfoAuthorize();
    }

    @OnClick(R.id.zm_get)
    public void onViewClicked() {
        zhima_cer();
    }
}
